<template>
  <div class='code btn' @click="handleGetCode">
    {{text}} </div>
</template>
<script>
  import * as API from '@/api/index';

  export default {
    name: 'getCode',
    props: { 
      phone: {
        type: String,
        default: null
      },
      status: {
        type: Boolean,
        default: false
      },
      ChangeType: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        time: '获取验证码',
        start: true //倒计时没有为0 ，就不能继续调取接口
      };
    }, 
    computed: {
      text() {
        if (!isNaN(this.time)) {
          return this.time > 0 ? `${this.time}s后再次获取` : '获取验证码';
        }
        return '获取验证码';
      }
    },
    methods: {
      async handleGetCode() { 
         if(!this.start) return false;
          if (this.phone != null && this.phone.length >= 11) { 
            const data = {
              service: 'Pro.User.SendMsg',
              type: this.ChangeType,
              phone: this.phone
            };
            const res = await API.toIndex(data);
            if (res.ret == 200) {
              this.start = false;
               this.$notify({
                title: '发送信息',
                message: res.msg,
                type: 'success'
              });
            this.status && this.set();
            this.$emit('update:status', false); 
            } else { 
               this.$notify({
                title: '警告',
                message: res.msg,
                type: 'warning'
              });
            }  
          } else {
            this.$notify.error({
              title: '错误',
              message: '请填写手机号码'
            });
          }     

      },
      set() {
        this.time = 60;
        const timer = setInterval(() => {
          this.time--;
          if (this.time === 0) {
            this.start = true;
            this.$emit('handleGetCode');
            this.time = '获取验证码';
            this.$emit('update:status', true);            
            clearInterval(timer);
          }
        }, 1000);
      }
    }
  };

</script>
<style lang="css" scoped>
  .bgColor {
    background: #fcd953;
    padding: 12px 10px;
    border-radius: 50px;
    font-size: 22px;
  }

</style>
